from django.shortcuts import render, redirect, HttpResponse
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.http.response import JsonResponse
from django.views import View
from django import forms
import hashlib
from app01 import models


# 加盐的md5加密
def get_md5_str(str1):
	"""hashlib加盐的md5加密字符串"""
	md5_obj = hashlib.md5("锄禾日当午".encode("utf-8"))
	md5_obj.update(str1.encode("utf-8"))
	return md5_obj.hexdigest()


class AddUserForm(forms.Form):
	'''添加用户form组件'''
	username = forms.CharField(
		label='用户名',
		error_messages={
			'required': '此字段为必填项',
		},
		widget=forms.TextInput(
			attrs={'class': 'form-control'}
		),
	)
	password = forms.CharField(
		label='密码',
		min_length=6,
		widget=forms.PasswordInput(
			attrs={'class': 'form-control'}
		),
		error_messages={
			'required': '此字段为必填项',
			'min_length': '密码至少为6位'
		}
	)
	repassword = forms.CharField(
		label='确认密码',
		widget=forms.PasswordInput(
			attrs={'class': 'form-control'}
		),
		error_messages={
			'required': '此字段为必填项'
		}
	)
	phone = forms.CharField(
		label='手机号',
		error_messages={
			'required': '此字段为必填项'
		},
		widget=forms.TextInput(
			attrs={'class': 'form-control'}
		),
		validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机格式有误')]
	)
	dep_list = models.Department.objects.all()
	dep_choice_list = []
	for dep_obj in dep_list:
		dep_choice_list.append((dep_obj.pk, dep_obj.name))

	dep = forms.ChoiceField(
		label='部门',
		choices=dep_choice_list,
		widget=forms.Select(
			attrs={'class': 'form-control'}
		)
	)

	def clean_username(self):
		'''局部钩子，校验用户名长度和敏感信息'''
		username = self.cleaned_data.get('username')
		if len(username) < 6:
			raise ValidationError('用户名至少6位')
		if 'alex' in username:
			raise ValidationError('用户名含有敏感信息')
		return username

	def clean(self):
		'''全局钩子，两次密码是否一至'''
		password = self.cleaned_data.get('password')
		repassword = self.cleaned_data.get('repassword')
		if password == repassword:
			return self.cleaned_data
		self.add_error('repassword', '两次密码不一致')
		raise ValidationError("两次密码不一致")


class AddUser(View):
	'''添加用户'''
	def get(self, request):
		usr = request.session.get('usr')
		userForm_obj = AddUserForm()
		return render(request, 'addUser.html', locals())

	def post(self, request):
		userForm_obj = AddUserForm(request.POST)
		if userForm_obj.is_valid():
			username = request.POST.get('username')
			password = request.POST.get('password')
			phone = request.POST.get('phone')
			dep = request.POST.get('dep')
			dep = int(dep)
			models.UserInfo.objects.create(
				username=username,
				password=get_md5_str(password),
				phone=phone,
				dep_id=dep
			)
			return redirect('userList')
		return render(request, 'addUser.html', locals())


class UserList(View):
	'''用户列表'''
	def get(self, request):
		user_list = models.UserInfo.objects.all()
		usr = request.session.get('usr')
		return render(request, 'userList.html', locals())


class EditUser(View):
	'''编辑用户'''
	def get(self, request, pk):
		usr = request.session.get('usr')
		user_obj = models.UserInfo.objects.filter(id=pk).first()

		class EditUserForm(AddUserForm):
			username = forms.CharField(
				label='用户名',
				error_messages={
					'required': '此字段为必填项',
				},
				initial=user_obj.username,
				disabled=True,
				widget=forms.TextInput(
					attrs={'class': 'form-control'}
				),
			)
			password = forms.CharField(
				label='密码',
				min_length=6,
				widget=forms.PasswordInput(
					attrs={'class': 'form-control'}
				),
				error_messages={
					'min_length': '密码至少为6位'
				},
				required=False
			)
			repassword = forms.CharField(
				label='确认密码',
				widget=forms.PasswordInput(
					attrs={'class': 'form-control'}
				),
				required=False
			)
			phone = forms.CharField(
				label='手机号',
				error_messages={
					'required': '此字段为必填项'
				},
				validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机格式有误')],
				initial=user_obj.phone,
				widget=forms.TextInput(
					attrs={'class': 'form-control'}
				),
			)
			dep_list = models.Department.objects.all()
			dep_choice_list = []
			for dep_obj in dep_list:
				dep_choice_list.append((dep_obj.pk, dep_obj.name))

			dep = forms.ChoiceField(
				label='部门',
				choices=dep_choice_list,
				initial=user_obj.dep_id,
				widget=forms.Select(
					attrs={'class': 'form-control'}
				)
			)

		userForm_obj = EditUserForm()
		return render(request, 'editUser.html', locals())

	def post(self, request, pk):
		usr = request.session.get('usr')
		user_obj = models.UserInfo.objects.filter(id=pk).first()

		class EditUserForm(AddUserForm):
			username = forms.CharField(
				label='用户名',
				error_messages={
					'required': '此字段为必填项',
				},
				initial=user_obj.username,
				disabled=True,
				widget=forms.TextInput(
					attrs={'class': 'form-control'}
				),
			)
			password = forms.CharField(
				label='密码',
				min_length=6,
				widget=forms.PasswordInput(
					attrs={'class': 'form-control'}
				),
				error_messages={
					'min_length': '密码至少为6位'
				},
				required=False
			)
			repassword = forms.CharField(
				label='确认密码',
				widget=forms.PasswordInput(
					attrs={'class': 'form-control'}
				),
				required=False
			)
			phone = forms.CharField(
				label='手机号',
				error_messages={
					'required': '此字段为必填项'
				},
				validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机格式有误')],
				widget=forms.TextInput(
					attrs={'class': 'form-control'}
				),
			)
			dep_list = models.Department.objects.all()
			dep_choice_list = []
			for dep_obj in dep_list:
				dep_choice_list.append((dep_obj.pk, dep_obj.name))

			dep = forms.ChoiceField(
				label='部门',
				choices=dep_choice_list,
				widget=forms.Select(
					attrs={'class': 'form-control'}
				)
			)

		userForm_obj = EditUserForm(request.POST)
		if userForm_obj.is_valid():
			password = request.POST.get('password')
			phone = request.POST.get('phone')
			dep = request.POST.get('dep')
			dep = int(dep)
			if password:
				models.UserInfo.objects.filter(id=pk).update(
					password=get_md5_str(password),
					phone=phone,
					dep_id=dep
				)
			else:
				models.UserInfo.objects.filter(id=pk).update(
					phone=phone,
					dep_id=dep
				)
			return redirect('userList')
		return render(request, 'editUser.html', locals())


class DelUser(View):
	'''删除用户'''
	def post(self, request):
		pk = request.POST.get('pk')
		models.UserInfo.objects.filter(pk=pk).delete()
		return JsonResponse({'status': '用户删除成功'})


class LoginForm(forms.Form):
	username = forms.CharField(
		label='用户名',
		error_messages={
			'required': "用户名不能为空"
		},
		widget=forms.TextInput(
			attrs={'class': 'form-control'}
		)
	)
	password = forms.CharField(
		label='密码',
		widget=forms.PasswordInput(
			attrs={'class': 'form-control'}
		),
		error_messages={
			'required': "密码不能为空"
		},
	)


class Login(View):
	'''用户登录'''
	def get(self, request):
		loginForm_obj = LoginForm()
		return render(request, 'login.html', locals())

	def post(self, request):
		loginForm_obj = LoginForm(request.POST)
		if loginForm_obj.is_valid():
			username = request.POST.get('username')
			password = request.POST.get('password')
			user_exists = models.UserInfo.objects.filter(username=username, password=get_md5_str(password)).exists()
			if user_exists:
				# 登录成功
				request.session['usr'] = username
				return_url = request.GET.get('return_url')
				if return_url:
					return redirect(return_url)
				return redirect('userList')
		error = '用户名或密码错误'
		return render(request, 'login.html', locals())


class Logout(View):
	'''退出'''
	def get(self, request):
		request.session.flush()
		return redirect('login')

